package com.wanxi.spring.cloud.security.aspect;

import com.wanxi.spring.cloud.commons.api.CommonResult;
import com.wanxi.spring.cloud.security.esModel.EsLog;
import com.wanxi.spring.cloud.security.model.Log;
import com.wanxi.spring.cloud.security.model.User;
import com.wanxi.spring.cloud.security.repository.LogRepository;
import com.wanxi.spring.cloud.security.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class LoggingAspect {

    @Autowired
    LogService logService;
    @Autowired
    LogRepository logRepository;

    @Pointcut("execution(* com.wanxi.spring.cloud.security.service.impl.UserServiceImpl.login(..))")
    public void pointcut(){

    }

    //在该方法执行之后运行
    @AfterReturning(returning="rvt",pointcut = "pointcut()")
    public void afterReturning(JoinPoint joinPoint, CommonResult rvt){
        System.out.println(rvt);
        if (rvt.getCode()==200){//如果返回值为200则登录成功，记录登录日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            //参数名称
            String[] names=((MethodSignature) joinPoint.getSignature()).getParameterNames();
            //参数值
            Object[] objects=joinPoint.getArgs();
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < names.length; i++) {
                map.put(names[i], objects[i]);
            }
            User user = (User)map.get("user");

            Log log = new Log();
            //格式化登录时间
            String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            //获取IP地址
            InetAddress addr = null;
            try {
                addr = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String ip = addr.getHostAddress();//获得本机IP
            String address = addr.getHostName();//获得本机名称
            log.setUserCode(user.getCode()).setLoginTime(sdf).setIpAddress(ip + " " + address);
            //将日志存入数据库
            logService.addLog(log);
            EsLog esLog = new EsLog();
            BeanUtils.copyProperties(log, esLog);//深拷贝一份到esLog
//        将登录日志存入到elasticsearch
            try {
                logRepository.save(esLog);
            } catch (Exception e) {
                System.out.println("elasticsearch未开启");
            }
        }
    }
}
